export function msg(content, time = 3000) {
  uni.showToast({
    icon: 'none',
    title: content,
    duration: time,
  })
}

export function showLoading(content = '加载数据中...', mask = true) {
  uni.showLoading({
    title: content,
    mask: mask,
  })
}

export function hideLoading(timer = 0) {
  if (timer > 0) {
    var t = setTimeout(function () {
      uni.hideLoading()
      clearTimeout(t)
    }, timer)
  } else {
    uni.hideLoading()
  }
}

export function in_array(search, array) {
  let flag = false
  for (let i in array) {
    if (array[i] == search) {
      flag = true
      break
    }
  }

  return flag
}

export function isDataType(data, type) {
  return Object.prototype.toString.call(data) === '[object ' + type + ']'
}

export function ltrim(str, char) {
  let pos = str.indexOf(char)
  let sonstr = str.substr(pos + 1)
  return sonstr
}

export function rtrim(str, char) {
  let pos = str.lastIndexOf(char)
  let sonstr = str.substr(0, pos)
  return sonstr
}

/**
 * 保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面。
 */
export function navigateTo(url, params) {
  console.log(url,params);
  uni.navigateTo({
    url: parseUrl(url, params),
  })
}

/**
 * 关闭当前页面，跳转到应用内的某个页面。
 */
export function redirectTo(url, params) {
  uni.redirectTo({
    url: parseUrl(url, params),
  })
}

/**
 * 关闭所有页面，打开到应用内的某个页面。
 */
export function reLaunch(url, params) {
  uni.reLaunch({
    url: parseUrl(url, params),
  })
}

/**
 * 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
 */
export function switchTab(url, params) {
  uni.switchTab({
    url: parseUrl(url, params),
  })
}

/**
 * 关闭当前页面，返回上一页面或多级页面
 */
export function navigateBack(delta) {
  uni.navigateBack({
    delta: delta,
  })
}

/**
 * 预加载页面，是一种性能优化技术。被预载的页面，在打开时速度更快。
 */
export function preloadPage(url, params) {
  uni.preloadPage({
    url: parseUrl(url, params),
  })
}

export function prePage() {
  let pages = getCurrentPages()
  let prePage = pages[pages.length - 2]
  // #ifdef H5
  return prePage
  // #endif
  return prePage.$vm
}

/**
 * rpx转px
 * @param int|float num
 */
export function rpx2px(num) {
  // const info = uni.getSystemInfoSync()
  // let scale = 750 / info.windowWidth;
  // return (Number.isNaN(parseFloat(num)) ? 0 : parseFloat(num)) / scale;
  return uni.upx2px(num)
}

/**
 * @param int|float num
 */
export function px2rpx(num) {
  return num / (uni.upx2px(num) / num)
}

/**
 * 获取窗口的宽高
 */
export function getSystemInfo() {
  const info = uni.getSystemInfoSync()
  return {
    w: info.windowWidth,
    h: info.windowHeight,
  }
}

function parseUrl(url, params) {
  let arr = []
  let string = ''
  for (let i in params) {
    arr.push(i + '=' + params[i])
  }

  string = '/pages/' + url
  if (arr.length > 0) {
    string += '?' + arr.join('&')
  }

  return string
}
// 时间戳转成日期格式
export function formatTime(time, formatStr = '-', hasjoin = true) {
  let date = new Date(time)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  if (hasjoin) {
    return (
      [year, month, day].map(formatNumber).join(formatStr) +
      ' ' +
      [hour, minute, second].map(formatNumber).join(':')
    )
  } else {
    return {
      date: [year, month, day].map(formatNumber),
      time: [hour, minute, second].map(formatNumber),
    }
  }
}

export function formatTimeDay(time, formatStr = '-') {
  let date = new Date(time)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join(formatStr)
}
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export function formatDay(time, formatStr = '-') {
  let date = new Date(time)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join(formatStr)
}

export function getStorageSync(key) {
  var value = ''
  try {
    value = uni.getStorageSync(key)
  } catch (e) {
    // Do something when catch error
  }
  return value
}
export function removeStorageSync(key) {
  try {
    uni.removeStorageSync(key)
  } catch (e) {
    // Do something when catch error
  }
}

export function clearStorageSync() {
  try {
    uni.clearStorageSync()
  } catch (e) {
    // error
  }
}

export function setStorageSync(key, value) {
  try {
    uni.setStorageSync(key, value)
  } catch (e) {
    // error
  }
}

// 节流
export function throttle(fn, delay = 1000) {
  let timer = null
  let firstTime = true

  return function (...args) {
    if (firstTime) {
      // 第一次加载
      fn.apply(this, args)
      return (firstTime = false)
    }
    if (timer) {
      // 定时器正在执行中，跳过
      return
    }
    timer = setTimeout(() => {
      clearTimeout(timer)
      timer = null
      fn.apply(this, args)
    }, delay)
  }
}
// 防抖
export function debounce(func, delay) {
  let timeout
  return function () {
    let context = this // 指向全局
    let args = arguments
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      func.apply(context, args) // context.func(args)
    }, delay)
  }
}
//判断浏览器是否是微信浏览器
export function checkIsWechatBrowser(){
  return (
    navigator.userAgent.toLowerCase().match(/MicroMessenger/i) ==
    "micromessenger"
  );
}

//微信浏览器中打开H5隐藏顶部导航方法
export function hidePageNavInWechatBrowser(){
  //#ifdef H5
  if (checkIsWechatBrowser()) {
    let pageNav = document.getElementsByTagName("uni-page-head");
    if (pageNav && pageNav[0]) {
      pageNav[0].style.display = "none";
    }
  }
  //#endif
}
// 拨打电话
export function callPhone(tel){
  uni.makePhoneCall({
    phoneNumber: tel
  })
}

// 实现rich-text富文本中图片宽度最大100%function formatContent (html) { // 去掉img标签里的style、width、height属性
export function formatRichContent(html){
  let content_data = "";
  if(html && html!=""){
     content_data= html.replace(/<img[^>]*>/gi,function(match,capture){
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    }); // 修改所有style里的width属性为max-width:100%
    content_data = content_data.replace(/style="[^"]+"/gi,function(match,capture){
      match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
      return match;
    }); // 去掉<br/>标签
    content_data = content_data.replace(/<br[^>]*\/>/gi, ''); // img标签添加style属性：max-width:100%;height:auto
    content_data = content_data.replaceAll('http://gykj123.cn:9032','https://dev.agribigdata.com.cn');
    content_data = content_data.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0px auto;"'); 
  }
  return content_data;
}

export function getVideoBase64(url) {
  return new Promise(function (resolve, reject) {
      let dataURL = '';
      let video = document.createElement("video");
      video.setAttribute('crossOrigin', 'anonymous');//处理跨域
      video.setAttribute('preload', 'auto');
      video.setAttribute('src', url);
      video.setAttribute('width', 400);
      video.setAttribute('height', 240);
      video.addEventListener('loadeddata', function () {
          let canvas = document.createElement("canvas"),
              width = video.width, //canvas的尺寸和图片一样
              height = video.height;
          canvas.width = width;
          canvas.height = height;
          canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
          dataURL = canvas.toDataURL('image/png'); //转换为base64
          resolve(dataURL);
      });
  })
}